import { V } from "x-engine";
import * as nunjucks from "nunjucks";
import * as glob from "glob";
import * as path from "path";
import { X } from "x-orm";
import * as fs from "fs";
let yaml = require("js-yaml");


const ROOT_PATH = path.resolve(__dirname);

export function start (){

    let argMap = {};
    for (let key = 0; key < process.argv.length; key++) {
        const val = process.argv[key];
        if (val[0] === '-') {
            if (process.argv.hasOwnProperty(key + 1)) {
                argMap[val] = process.argv[key + 1];
            }
        }
    }

    process.on("uncaughtException", (e) => {
        console.log(e);
    });

    let config = yaml.safeLoad(fs.readFileSync('../../config.yml', 'utf8'));
    let defaultConfig = {
        server: {
            port: argMap['-p'] || 8080,
        },
        service: {
            port: argMap['-p'] || 8090,
        },
        database: {
            use: false,
            datasource: []
        }
    };
    config = Object.assign(defaultConfig, config);

    for (const db of config.database.datasource) {
        db.password += "";
    }

    //启用数据库
    if(config.database.use){
        X.startORM(config.database);
    }


    //加载控制器
    const dirs = glob.sync(ROOT_PATH + "/app/*");
    for (const dir of dirs) {
        fs.lstat(dir, (err, stat) => {
            if (err) {
                return;
            }
            if (!stat.isDirectory()) {
                return;
            }
            //自动加载控制器
            let ctrlDir = dir + '/controller';
            fs.exists(ctrlDir, ex => {
                if (!ex) {
                    return;
                }
                V.addHotUpdateDir(ctrlDir);
                glob(ctrlDir + '/*.js', (err, files) => {
                    if (err) {
                        return;
                    }
                    for (const file of files) {
                        require(file);
                    }
                });
            });
            //加载入口文件
            fs.exists(dir + '/main.js', ex => {
                if (!ex) {
                    return;
                }
                let p = require(dir + '/main.js');
                if (p.onLoad) {
                    p.onLoad.call(null, dir);
                }
            })

        });
    }
  
    return config;

};




